<?php
namespace app\admin\controller;
use think\Config;
use app\admin\model\User as UserModel;
use think\Request;
use app\admin\model\Api as ApiModel;

class User extends Base
{
    public function index()
    {
        if(!$this->isRoot()){
            $this->redirect('/admin');
        }
        return $this->fetch();
    }

    public function all_user_list(Request $request)
    {
        $page = $request->param('page');
        $model = new UserModel();
        $list = $model->getUserList($page);
        if(is_array($list) || is_object($list)){
            return ajaxReturn($list,$model->count);
        }else{
            return ajaxReturn('查询错误');
        }
    }

    public function user_add(Request $request)
    {
        if(!$this->isRoot()){
            return ajaxReturn('此模块只允许超级管理员使用');
        }
        $name = $request->param('name');
        $model = new UserModel();
        $model->name = $name;
        $time = time();
        $model->create_time = $time;
        if($model->save()){
            return ajaxReturn(['id'=>$model->id,'name'=>$name,'create_time'=>date('Y-m-d H:i:s'),'status'=>1,'statusMsg'=>'正常']);
        }else{
            return ajaxReturn('添加失败');
        }

    }

    //编辑用户
    public function user_edit(Request $request)
    {
        if(!$this->isRoot()){
            return ajaxReturn('此模块只允许超级管理员使用');
        }
        $name = $request->param('name');
        $id = $request->param('id');
        if(!$name || !$id){
            return ajaxReturn('参数错误');
        }
        $model = new UserModel();
        $result = $model->save([
            'name'  => $name
        ],['id' => $id]);

        if($result){
            return ajaxReturn([]);
        }else{
            return ajaxReturn('编辑失败');
        }
    }

    //禁用启用处理
    public function user_status_edit_do(Request $request)
    {
        if(!$this->isRoot()){
            return ajaxReturn('此模块只允许超级管理员使用');
        }
        $param = $request->param();
        if(!$param['id']){
            return ajaxReturn('参数错误');
        }

        if($param['id'] == Config::get('root')){
            return ajaxReturn('最高管理员不能禁用');
        }

        UserModel::update([
            'id' => $param['id'],
            'status' => $param['status']
        ]);
        return ajaxReturn([]);
    }

    public function user_del(Request $request)
    {
        if(!$this->isRoot()){
            return ajaxReturn('此模块只允许超级管理员使用');
        }
        $id = $request->param("id");
        if($id == Config::get('root')){
            return ajaxReturn('最高管理员不能删除');
        }
        $user = UserModel::get($id);
        if($user->delete()){
            ApiModel::destroy(['user_id' => $id]);
            return ajaxReturn([]);
        }else{
            return ajaxReturn('删除失败');
        }

    }

}
